<?php



/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
 
class Game_Plugin_Core
{
  public function onStatistics($event)
  {
    $table   = Engine_Api::_()->getDbTable('games', 'game');
    
    $select = new Zend_Db_Select($table->getAdapter());
    $select->from($table->info('name'), 'COUNT(*) AS count');
    $select->where("status = ?", Game_Model_Game::STATUS_PUBLISHED);
    $select->where("search = ?", 1);
    $event->addResponse($select->query()->fetchColumn(0), 'game');
  }


  public function onUserDeleteBefore($event)
  {
    $payload = $event->getPayload();
    if( $payload instanceof User_Model_User ) {
      // Delete games
      $gameTable = Engine_Api::_()->getDbtable('games', 'game');

      $gameSelect = $gameTable->select()->where('user_id = ?', $payload->getIdentity());
      foreach( $gameTable->fetchAll($gameSelect) as $game ) {
        $game->delete();
      }

      $scoreTable = Engine_Api::_()->getDbtable('scores', 'game');
      $scoreSelect = $scoreTable->select()->where('user_id = ?', $payload->getIdentity());
      foreach ($scoreTable->fetchAll($scoreSelect) as $score) {
        $score->delete();
      }
      
      $favoriteTable = Engine_Api::_()->getDbtable('favorites', 'game');
      $favoriteSelect = $favoriteTable->select()->where('user_id = ?', $payload->getIdentity());
      foreach ($favoriteTable->fetchAll($favoriteSelect) as $favorite) {
        $game = $favorite->getParent();
        $game->favorites()->removeFavorite($payload);
      }
    }
  }

}